#!/bin/bash
# formate for timetable:
# 3:00    4:00
# 5:23    06:07

if [ $# != 2 ]; then
    echo "Usage: ff_extract.sh timetable inputfile"
    exit 1
fi

timetable=$1
inputfile=$2
suffix=${inputfile##*.}
filename=${inputfile%.*}

# converts HH:MM:SS.sss to fractional seconds
codes2seconds() (
  local hh=${1%%:*}
  local rest=${1#*:}
  local mm=${rest%%:*}
  local ss=${rest#*:}
  printf "%s" $(bc <<< "$hh * 60 * 60 + $mm * 60 + $ss")
)

# converts fractional seconds to HH:MM:SS.sss
seconds2codes() (
  local seconds=$1
  local hh=$(bc <<< "scale=0; $seconds / 3600")
  local remainder=$(bc <<< "$seconds % 3600")
  local mm=$(bc <<< "scale=0; $remainder / 60")
  local ss=$(bc <<< "$remainder % 60")
  printf "%02d:%02d:%06.3f" "$hh" "$mm" "$ss"
)

subtracttimes() (
  local t1sec=$(codes2seconds "$2")
  local t2sec=$(codes2seconds "$1")
  printf "%s" $(bc <<< "$t2sec - $t1sec")
)

[ ! -d "tmp" ] && mkdir ./tmp
prefix="video"
counter=1
mergefile='./tmp/merge.list'

cat $timetable | while read stime etime; do
    echo "read time span, stime:${stime}, etime:${etime}"
    printf -v num "%02d" $counter
    tmpfile="${prefix}${num}.${suffix}"
    duration=$(subtracttimes ${etime} ${stime})
    #ffmpeg -nostdin -ss "${stime}" -t "${duration}" -i "${inputfile}" -c:v copy -c:a copy -async 1 "./tmp/${tmpfile}"
    endtime=$(seconds2codes $duration) 
    echo "${stime} -- ${endtime}" 
    ffmpeg -nostdin -ss "${stime}" -t "${endtime}" -i "${inputfile}" -c:v copy -c:a copy -async 1 "./tmp/${tmpfile}"
    echo "file '${tmpfile}'" >> $mergefile 
    counter=$[$counter+1]
done

ffmpeg -f concat -safe 0 -i "${mergefile}" -c copy "${filename}_selected.${suffix}"
[ -d "tmp" ] && rm -fr ./tmp
